package com.blkj.framework.auth;

import com.blkj.common.exception.user.UserSessionInvalidException;
import com.blkj.common.utils.ServletUtils;
import com.blkj.framework.auth.util.FilterUtil;
import com.blkj.framework.config.AuthPropertiesConfig;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限过滤器
 */
@WebFilter(filterName = "authFilter",urlPatterns = "/admin/*")
public class AuthFilter implements Filter {

    @Autowired
    AuthPropertiesConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

       //静态资源放行
        if (FilterUtil.isStaticResource(request)){
            filterChain.doFilter(request,response);
            return;
        }


        if (config.isMatch(request)){
            //判断是否登陆
            Object user = request.getSession().getAttribute("user");
            if (null == user){
                if (ServletUtils.isAjaxRequest(request)){
                    request.setAttribute("error",new UserSessionInvalidException());
                    request.getRequestDispatcher("/error").forward(servletRequest,servletResponse);
                }
                request.getSession().setAttribute("lastUrl",request.getRequestURI());
                response.sendRedirect("/admin/login");
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
